package com.teamsun.controller;

import com.teamsun.annotation.PublicHandlerMethod;
import com.teamsun.entity.UserInfo;
import com.teamsun.entity.VersionInfo;
import com.teamsun.exception.ServiceException;
import com.teamsun.system.ILoginService;
import com.teamsun.system.ISysService;
import com.teamsun.util.Constants;
import com.teamsun.util.MD5Util;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * 报表登录Controller
 */
@Controller
public class LoginController {
    private static final Logger LOGGER = Logger.getLogger(LoginController.class);

    @Autowired
    private ILoginService loginService;

    @Autowired
    private ISysService sysService;

    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 无Session登录
     * @return
     */
    @RequestMapping("/noSession")
    @PublicHandlerMethod
    public String noSession() {
        return "../login";
    }

    /**
     * 登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login")
    @PublicHandlerMethod
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String userCode = request.getParameter("userCode");
        String password = request.getParameter("password");

        try {
            if(StringUtils.isEmpty(userCode)) {
                throw new ServiceException("用户名不能为空");
            } else if(StringUtils.isEmpty(password)) {
                throw new ServiceException("密码不能为空");
            }

            // 校验用户是否登录成功
            String encodePassword = MD5Util.md5LowerCase(password);
            UserInfo user = loginService.verifyLoginInfo(userCode, encodePassword);
            // 登录成功，跳转至系统首页
            request.getSession().setAttribute(Constants.SESSION_USER, user);
            request.setAttribute("userName", user.getUserName());
            request.setAttribute("isAdmin", user.getAdmin());  // 用户是否是管理员

            // 查询是否有版本跟新信息
            String showUpdate = "1";
            VersionInfo versionInfo = sysService.queryLatestVersion();
            // 如果当前时间距更新时间在10天内，前台有更新提示，超过10天无提示
            if(versionInfo != null) {
                String createDate = versionInfo.getCreateDate();
                Calendar versionCalendar = Calendar.getInstance();
                versionCalendar.setTime(FORMATTER.parse(createDate));
                versionCalendar.add(Calendar.DATE, 10);

                Calendar now = Calendar.getInstance();
                if(versionCalendar.compareTo(now) < 0) {
                    showUpdate = "0";
                }
            }
            request.setAttribute("showUpdate", showUpdate);

            return "../WEB-INF/page/index";
        } catch (ServiceException e) {
            // 登录失败，重新跳转至登录页面
            request.setAttribute("userCode", userCode);
            request.setAttribute("password", password);
            request.setAttribute("errorMsg", e.getMessage());
            return "../login";
        } catch (Exception e) {
            // 登录失败，重新跳转至登录页面
            LOGGER.error(e.getMessage(), e);
            request.setAttribute("errorMsg", "登录异常");
            return "../login";
        }
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute(Constants.SESSION_USER);
        request.getSession().invalidate();

        return "../login";
    }
}
